import logging
from django.views.decorators.http import require_GET
from django.views.generic import TemplateView
from common.permission import db, handler
from django.utils.decorators import method_decorator
from common.utils.decorator import response_wrapper, validate_form
from common.utils.api import token_required
from .permission_form import PermissionListForm, GetKeyMapperForm

_LOGGER = logging.getLogger(__name__)


class PermissionView(TemplateView):
    @method_decorator(validate_form(PermissionListForm))
    def get(self, req, cleaned_data):
        items, total_count = db.list_perm(cleaned_data)
        resp_items = []
        for item in items:
            item['updated_at'], item['created_at'] = str(item['updated_at']), str(item['created_at'])
            resp_items.append(item)
        return dict(list=resp_items, page=cleaned_data.get('page', 1), size=len(resp_items), total_count=total_count)

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(PermissionView, self).dispatch(*args, **kwargs)


class SinglePermissionView(TemplateView):
    def get(self, req, perm_id):
        perm_id = int(perm_id)
        perm = db.get_perm(dict(id=perm_id)).__dict__ or {}
        perm.pop('_state', None)
        perm['created_at'], perm['updated_at'] = str(perm.get('created_at')), str(perm.get('updated_at'))
        return perm

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(SinglePermissionView, self).dispatch(*args, **kwargs)


@require_GET
@token_required
@response_wrapper
@validate_form(GetKeyMapperForm)
def get_page_key_mapper(req, cleaned_data):
    merchant_name = req.merchant_name
    page_id = cleaned_data['page_id']
    return handler.get_key_mapper(merchant_name, page_id)


@require_GET
@response_wrapper
def get_user_menu_list(req):
    merchant_id = req.merchant_id
    merchant_role = req.merchant_role
    is_root = req.is_root
    return handler.get_user_menu_list(merchant_id, merchant_role, is_root)
